package com.lhj.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhj.crm.entity.DeptRole;
import com.lhj.crm.entity.Role;
import com.lhj.crm.mapper.DeptRoleMapper;
import com.lhj.crm.mapper.RoleMapper;
import com.lhj.crm.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FYI
 * @since 2020-03-23
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private DeptRoleMapper deptRoleMapper;

    @Override
    public IPage<Role> selectPageList(Page<Role> rolePage) {
        IPage<Role> roleIPage = roleMapper.selectPageList(rolePage);
        return roleIPage;
    }

    @Override
    public Role selectByName(String roleName) {
        return roleMapper.selectByName(roleName);
    }

    @Override
    public Role selectById(Integer roleId) {
        return roleMapper.selectById(roleId);
    }

    /*修改*/
    @Override
    public Integer update(Role role, Integer permId,Integer deptId) {

        role.setUpdateTime(new Date());
        int result = roleMapper.updateById(role);

        //修改部门和角色关系表
        DeptRole deptRole = new DeptRole(deptId,role.getRoleId());
        deptRole.setUpdateTime(new Date());
        AbstractWrapper wrapper = new QueryWrapper();
        wrapper.eq("role_id",role.getRoleId());
        deptRoleMapper.update(deptRole,wrapper);
        return result;
    }

    /*添加*/
    @Override
    public Integer addRole(Role role, Integer permId,Integer deptId) {

        role.setCreateTime(new Date());
        role.setUpdateTime(role.getCreateTime());
        role.setIsDel(0);

        int result = roleMapper.insert(role);

         //获取插入自增的id
        Integer roleId = role.getRoleId();
        //将empId和roleId一同插入到  员工与角色关系表
        DeptRole deptRole = new DeptRole(deptId,roleId);
        deptRole.setCreateTime(new Date());
        deptRole.setUpdateTime(deptRole.getCreateTime());
        deptRole.setIsDel(0);
        deptRoleMapper.insert(deptRole);

        return result;
    }


}
